function BookmarkListController(){ }
 
BookmarkListController.prototype.params = {};
BookmarkListController.prototype.params.data = [];
BookmarkListController.prototype.params.newCreate = false;
BookmarkListController.prototype.params.cityName = '';

BookmarkListController.prototype.searchparams = {};

BookmarkListController.prototype.currentPage = false;

//params: title, data-params
BookmarkListController.prototype.pushParams = function(params) {
    BookmarkListController.prototype.params.data.push(params);
    BookmarkListController.prototype.params.newCreate = true;
};

BookmarkListController.prototype.popParams = function() {
    if (BookmarkListController.prototype.params.newCreate) {
        BookmarkListController.prototype.params.newCreate = false;
        return BookmarkListController.prototype.params.data[BookmarkListController.prototype.params.data.length - 1];
    } else {
        return BookmarkListController.prototype.params.data.pop();
    }
};

function CityListLoader(){
    this.pref = [];
    this.city = [];
}

$(function(){
    var cityListLoader;
    
    $(document).on('pageshow', '#pageBookmarkList', function(){
        PageChangeController.prototype.freeMemory();
        if (BookmarkListController.prototype.params.data.length <= 0 || BookmarkListController.prototype.currentPage) {
            Util.prototype.hideSpinner();
            return false;
        }
        var params = BookmarkListController.prototype.popParams();
        BookmarkListController.prototype.searchparams = params;
        
        monaca.updateUIStyle("titlelable", "text", params.title);
        monaca.updateUIStyle("footer", "visibility", "true");
        Util.prototype.changeSnapperElement("bookmarklistarchives-content");

        $('#pageBookmarkListTitle').html(params.title);

        // check pre Page
        if (params.fromPage === 'pageCityArchives') {            
            Util.prototype.showEditIcon(params.title);
            BookmarkListController.prototype.params.cityName = params.title;
        } else {
            Util.prototype.showEditIcon();
        }

        ProductListLoader.prototype.initLoadBookmarkList("true", params);
        ProductListLoader.prototype.loadProducts($('#archiveBookmarkList'), $(".bookmarklistarchives-pull"), null
        , "<li><h3>商品が見つかりませんでした</h3></li>");        
    });
    
    $(document).on('pageshow', '#pageBookmarkListSearch', function(){
        if (BookmarkListController.prototype.currentPage) {
            BookmarkListController.prototype.currentPage = false;
            Util.prototype.refreshPageScroller();
            Util.prototype.hideSpinner();
            return false;
        }
        PageChangeController.prototype.freeMemory();
        Util.prototype.showSpinner();
        monaca.updateUIStyle("titlelable", "text", "ブックマーク検索");
        monaca.updateUIStyle("backheader", "visibility", "true");
        monaca.updateUIStyle("footer", "visibility", "false");
        Util.prototype.changeSnapperElement("bookmarklistarchivessearch-content");
        // 詳細検索
        if (typeof BookmarkListController.prototype.searchparams.ym != 'undefined') {
            var fromYMD = BookmarkListController.prototype.searchparams.ym;
            var year = parseInt(fromYMD.slice(6,10), 10);
            var month = parseInt(fromYMD.slice(10), 10);
            var lastDay = Util.prototype.getNumberOfDays(year, month);
            if(month < 10){
                month = "0" + month; 
            }
            if(lastDay < 10){
                lastDay = "0" + lastDay; 
            }
            $('#fromYMD').val(year +'/'+ month +'/01');
            $('#toYMD').val(year +'/'+ month + '/' + lastDay);
        } else {
            var nowTerm = Util.prototype.addDays(0);
            $('#toYMD').val(nowTerm);    
        }
        if (typeof BookmarkListController.prototype.searchparams.keyword != 'undefined') {
            $('#keywordsearch').val(BookmarkListController.prototype.searchparams.title);
            $('#keywordsearchHidden').val(BookmarkListController.prototype.searchparams.keyword);
        }
        
        cityListLoader = new CityListLoader();
        
        BookmarksService.prototype.createBookmarkSearch(function(results) { // genres
            var len = results.rows.length;            
            var options = '<option value="">選択してください</option>';
            var selectedIndex = (typeof BookmarkListController.prototype.searchparams.genreCode != 'undefined') ? 0 : -1;
            for (var i=0; i<len; i++){ 
                options += '<option value="' + results.rows.item(i).genre_code;
                if (selectedIndex == 0 && BookmarkListController.prototype.searchparams.genreCode == results.rows.item(i).genre_code) {
                    console.log("current genre: " + results.rows.item(i).genre_code);
                    options += '" selected="true';
                    selectedIndex == (i + 1);
                }
                options += '">' + results.rows.item(i).name + '</option>';
            }
            $('#genresearch').append(options).selectmenu('refresh');
        }, function(results) { // pref
            var len = results.rows.length;            
            var options = '<option value="">選択してください</option>';
            var selectedIndex = (typeof BookmarkListController.prototype.searchparams.prefCode != 'undefined') ? 0 : -1;
            for (var i=0; i<len; i++){
                options += '<option value="' + results.rows.item(i).pref_no;
                if (selectedIndex == 0 && BookmarkListController.prototype.searchparams.prefCode == results.rows.item(i).pref_no) {
                    // console.log("current pref: " + results.rows.item(i).pref_no);
                    options += '" selected="true';
                    selectedIndex == (i + 1);
                }
                options += '">' + results.rows.item(i).pref_name + '</option>';
            }            
            $('#prefsearch').append(options).selectmenu('refresh');
        }, function(results) { // keyword
            var len = results.rows.length;
            var list = "";
            for (var i=0; i<len; i++){
                list += "<li id='keyDialogList"+results.rows.item(i).id+"' class='keyDialogList'>"+results.rows.item(i).name+"</li>";
            }
            $('#keyDialogList').append(list);
        });
        if (typeof BookmarkListController.prototype.searchparams.prefCode != 'undefined') {
            loadListCities(BookmarkListController.prototype.searchparams.prefCode);            
        } else {
            $('#citysearch').html('').append('<option value="">都道府県を選択してください</option>').selectmenu('refresh').selectmenu('disable');
        }
    });
    
    function loadListCities(prefNo) {
        var loaded = $.inArray(prefNo, cityListLoader.pref);
        if (loaded == -1) {
            BookmarksService.prototype.getHasProductByCity(prefNo, function(results) {
                cityListLoader.pref.push(prefNo);
                var cities = [];
                for (var i=0; i<results.rows.length; i++){
                    cities.push({'code': results.rows.item(i).code, 'city_name': results.rows.item(i).city_name});
                }
                cityListLoader.city.push(cities);
                
                layoutCitiesData(cities);
            });
        } else {
            layoutCitiesData(cityListLoader.city[loaded]);
        }
    }
    
    function layoutCitiesData(data) {
        $('#citysearch').html('');
        $('#citysearch').selectmenu('enable');
        var options = '<option value="">選択してください</option>';
        var selectedCity = (typeof BookmarkListController.prototype.searchparams.cityCode != 'undefined') ? 0 : -1;
        for (var i=0; i<data.length; i++){
            options += '<option value="' + data[i].code;
            if (selectedCity == 0 && BookmarkListController.prototype.searchparams.cityCode == data[i].code) {
                options += '" selected="true';
                selectedCity == (i + 1);
            }
            options += '">' + data[i].city_name + '</option>';
        }            
        $('#citysearch').append(options).selectmenu('refresh');
    }
    
    $('#prefsearch').change(function(){ 
        var selected = $(this).val();
        if (selected == '') {
            $('#citysearch').html('').append('<option value="">都道府県を選択してください</option>').selectmenu('refresh').selectmenu('disable');
        } else {
            loadListCities(selected);
        }
    });

    // キーワードセレクトメニュー（テキストボックス）タップ
    $(document).on('tap', '#keywordsearch', function(){
        BookmarkListController.prototype.currentPage = true;
        $('#showDialogKeyword').click();
        $("#keyDialogList").listview("refresh");
        return true;
    });

    // キーワードダイアログリストをタップ
    $(document).on('tap', '.keyDialogList', function(){
        $('#keywordsearch').val($(this).text());
        $('#keywordsearchHidden').val($(this).attr('id').slice(13));
        $('#dialogKeyword').dialog('close');
    });   
    
    // テスト用
    $(document).on('tap', '.editList', function(){
        if (Util.prototype.isSnapperClosed()) {
            PageChangeController.prototype.changeToPage('pageBookmarkRegister', {"bm_id" : $(this).attr('item-id'), "action" : 0});
        }
    });
    
    $(document).on('tap', '.listview-item', function() {
        if (Util.prototype.isSnapperClosed()) {
            var ilparams = {"id" : $(this).attr('id').slice(13)};
            monaca.retrieveUIStyle("footer", "visibility", function(footer) {
                if (footer == "true") {
                    if (!Util.prototype.isEditMode) {
                        PageChangeController.prototype.changeToPage('pageItemList', ilparams);
                    }
                } else {
                    PageChangeController.prototype.changeToPage('pageItemList', ilparams);
                }
            });            
        }
    });
    
    
    // 削除チェックボックスをタップ
    $(document).on('change', '.deleteCheck', function(){
        monaca.updateUIStyle("deletefooter", "disable", ($("[name='deleteCheck']:checked").length == 0) ? "true" :  "false");
    });
    
    $(document).on('tap', '#bl-control', function(){
        // TODO check type of Bookmarks List here in order to show options in the search page
        PageChangeController.prototype.changeToPage('pageBookmarkListSearch');
    });

    // 日付検索DatePicker
    $(document).on('tap', '.datepicker', function(){
        var targetId = $(this).attr('id');
        var myNewDate = new Date();
        if ($(this).attr('value') != ""){
            var year = $(this).attr('value').slice(0,4),
                month = $(this).attr('value').slice(5,7),
                date = $(this).attr('value').slice(8,10);
            myNewDate = new Date(year, month - 1, date);
        }

      // Same handling for iPhone and Android
        window.plugins.datePicker.show({
            date : myNewDate,
            mode : 'date', // date or time or blank for both
            allowOldDates : true
        }, function(returnDate) {
            var newDate = new Date(returnDate);
            var dpYMD = Util.prototype.createYMD(newDate);
            $('#'+targetId).val(dpYMD);
        });
      
        return false;
    });
    
    // 期間検索を選択→日付検索datepickerに反映させる
    $('#termsearch').change(function(){
        var selected = $(this).val();
        var nowYMD = Util.prototype.addDays(0);
                
        if(selected == "1"){ 
            //今日
            $('#fromYMD').val(nowYMD);
            $('#toYMD').val(nowYMD);
        }else if(selected == "2"){ 
            //1週間以内(7日前～今日)
            var aWeekAgoYMD = Util.prototype.addDays(-7);
            $('#fromYMD').val(aWeekAgoYMD);
            $('#toYMD').val(nowYMD);
        }else if(selected == "3"){ 
            //1か月以内(30日前～今日)
            var aMonthAgoYMD = Util.prototype.addDays(-30);
            $('#fromYMD').val(aMonthAgoYMD);
            $('#toYMD').val(nowYMD);   
        }else if(selected == "4"){
            //1年以内(365日前～今日)
            var aYearAgoYMD = Util.prototype.addDays(-365); 
            $('#fromYMD').val(aYearAgoYMD);
            $('#toYMD').val(nowYMD);
        }else if(selected == ""){
            //選択してください
            $('#fromYMD').val('');
            $('#toYMD').val(nowYMD);
        }
    });
    
    // 詳細検索ボタンクリック
    $(document).on('tap', '#bookmarkSchBtn', function(){
        //フリーワード、日付from、日付to、ジャンル、キーワード
        $('#colBookmarkSearch').click();
        var params = {'title': 'ブックマーク検索結果',
                      'wordsearch': $('#wordsearch').val(),
                      'fromymdsearch': $('#fromYMD').val(),
                      'toymdsearch': $('#toYMD').val(),
                      'genresearch': $('#genresearch').val(), 
                      'keywordsearch': $('#keywordsearchHidden').val(),
                      'prefsearch': $('#prefsearch').val(),
                      'citysearch': $('#citysearch').val()};
        
        PageChangeController.prototype.changeToPage('pageBookmarkList', params);
    });
    
    $(document).on('tap', '#bookmarkRstBtn', function() { 
        $('#wordsearch').val('');
        $('#termsearch').val('').selectmenu('refresh');
        $('#fromYMD').val('');
        $('#toYMD').val('');
        $('#genresearch').val('').selectmenu('refresh');
        $('#keywordsearch').val('');
        $('#keywordsearchHidden').val('');
        $('#prefsearch').val('').selectmenu('refresh');
        $('#citysearch').html('').append('<option value="">都道府県を選択してください</option>').selectmenu('refresh').selectmenu('disable');
        return false;
    });
    
    $(document).on('tap', '#keywordsearchDelete', function(){
        $('#keywordsearch').val("");
        return false;
    });
    
    BookmarkListController.prototype.checkAllCheckbox = function(){
        monaca.retrieveUIStyle("checkallfooter", "text", function(value) {
            var isSelectMode = (value == "すべて選択");
            $('.deleteCheck').prop('checked', isSelectMode).checkboxradio('refresh');
            monaca.updateUIStyle("checkallfooter", "text", isSelectMode? "すべて選択削除" : "すべて選択");
            monaca.updateUIStyle("deletefooter", "disable", isSelectMode ? "false" : "true");
        });        
    };
    
    BookmarkListController.prototype.showDeleteDialog = function(){
        var deleteNumber = $("[name='deleteCheck']:checked").length;
        navigator.notification.confirm(deleteNumber+"件のブックマークを削除しますか？", function(buttonIndex){
            if (buttonIndex == 1) {
                Util.prototype.showSpinner();
                
                var deleteIds = [],
                    updatedItems = [];
                var curListView = '';
                $('[name="deleteCheck"]:checked').each(function(){
                    var curId = $(this).val(),
                        status = $(this).attr('status'); /*0: bookmark delete, 1: scan delete, 2: bookmark update, 3: scan update*/
                    if (status == 2) {
                        updatedItems.push({id: curId, status: '1'});
                    } else {
                        deleteIds.push(curId);
                    }
                    
                    if(curListView == ''){
                        curListView = $('table#bookmarkTable' + curId).parent();
                    }
                    $('table#bookmarkTable' + curId).remove();
                });
                
                monaca.updateUIStyle("deletefooter", "disable", "true");
                var listChiNum = curListView.children().length;
                BookmarksService.prototype.deleteAdvanceBookmark(deleteIds, updatedItems, function() {
                    if ($.mobile.activePage.attr("id") == "pageCityArchives") {
                        if (listChiNum == 1) {
                            listChiNum = 0;                            
                        }                 
                        BookmarksService.prototype.countProductByCity(CityController.prototype.params.cityName, function(results) {
                            var len = results.rows.length,
                                list,
                                cityList = $('#cityList');
                            cityList.html('');
                            
                            for (var i=0; i<len; i++){
                                var item = results.rows.item(i);
                                if (i == 0){                                    
                                    list = "<li><a href='#' id = 'city" + item.pref_no + "' class = 'bookmarkCity bookmarkCity_Pref' city = " + item.pref_name + ">"+
                                            item.pref_name + " の一覧を表示<span class='ui-li-count'>" + item.citykazu+"</span></a></li>";    
                                } else {
                                    list += "<li><a href='#' id = 'city" + item.code + "' class = 'bookmarkCity' city = " + item.city_name + ">"+
                                            item.city_name + "<span class='ui-li-count'>" + item.citykazu+"</span></a></li>";       
                                }
                            }
                            if (typeof list != "undefined") {
                                cityList.append(list);
                            }
                            cityList.listview('refresh');
                        });
                    }
                    
                    if (listChiNum == 0) {
                        if (ProductListLoader.prototype.curProdPage == -1) {
                            monaca.updateUIStyle("footer", "visibility", "false");
                            curListView.append("<h3 stype='margin-top: 50px;'>ブックマーク登録がありません</h3>");
                            if ($.mobile.activePage.attr("id") == "pageHome") {
                                $('.tutorial').show("slow");
                            }
                            Util.prototype.hideSpinner();
                        } else { // continue load bookmarks
                            ProductListLoader.prototype.curProdPage = 0;
                            if ($.mobile.activePage.attr("id") == "pageBookmarkList") {
                                ProductListLoader.prototype.loadProducts(curListView, $(".bookmarklistarchives-pull"), null, "<li><h3>商品が見つかりませんでした</h3></li>");    
                            } else {
                                ProductListLoader.prototype.loadProducts(curListView, null, null, "<li><h3>商品が見つかりませんでした</h3></li>");
                            }                        
                        }
                    } else {
                        Util.prototype.hideSpinner();
                    }                                      
                });
            }
        }, "削除確認", ["削除","キャンセル"]);
    };
    
    BookmarkListController.prototype.freeMemory = function(isBmPage, isPageHome) {
        if (isBmPage) {
            $("#archiveBookmarkList").html('').listview('refresh');
        } else {
            cityListLoader = null;
            $('#genresearch').html('').selectmenu('refresh');
            $('#prefsearch').html('').selectmenu('refresh');
            $('#citysearch').html('').selectmenu('refresh');
            $('#keyDialogList').html('');
            $('#wordsearch').val('');
            $('#termsearch').val('').selectmenu('refresh');
            $('#fromYMD').val('');
            $('#toYMD').val('');
            $('#keywordsearch').val('');
            $('#keywordsearchHidden').val('');
        }
        if (isPageHome) {
            BookmarkListController.prototype.searchparams = {};
            BookmarkListController.prototype.params.data = [];
            BookmarkListController.prototype.params.newCreate = false;
            BookmarkListController.prototype.params.cityName = '';
            BookmarkListController.prototype.currentPage = false;
        }
    };
    
});